<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="50px"
    class="add-admin-form"
  >
    <el-form-item label="类型">
      <el-select
        v-model="form.type"
        placeholder="类型"
        clearable
      >
        <el-option
          v-for="(label, index) in typeList.value"
          :key="index"
          :label="label"
          :value="index"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="金额" prop="price">
      <el-input v-model="form.price" placeholder="请输入金额" type="number" />
      <div style="font-size: 12px; color: #999; margin-top: 5px;">正数为加负数为减</div>
    </el-form-item>
    <el-form-item label="备注" prop="price">
      <el-input v-model="form.remark" placeholder="备注" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" />
    </el-form-item>
  </el-form>
</template>

<script setup>
// filepath: d:\dockerphp\www\admin-ui\src\components\EditUserMoney.vue
import { ref, reactive, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

const props = defineProps({
  formData: {
    type: Object, // 修复为 Object 类型
    default: () => null
  },
  typeList: {
    type: Object, // 响应式对象
    default: () => ({ value: [] }) // 默认值为包含空数组的对象
  }
});

const formRef = ref(null);
const form = reactive({
  type: 0,
  price: 0,
  remark: ''
});

// 监听 formData 变化，更新表单数据
watch(() => props.formData, (newVal) => {
  if (newVal) {
    Object.assign(form, newVal); // 更新表单数据
  }
}, { immediate: true });

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(form, {
    price: 0,
    type: 0,
    remark: ''
  });
};

// 验证规则
const rules = {
  price: [
    { required: true, message: '请输入金额', trigger: 'blur' }
  ]
};

const validateForm = async () => {
  try {
    await formRef.value.validate();
    return true;
  } catch (error) {
    ElMessage.error('请检查表单填写是否正确');
    return false;
  }
};

onMounted(() => {
  console.log('typeList 数据:', props.typeList.value); // 打印 typeList 的值
  console.log('typeList 数据类型:', Array.isArray(props.typeList.value) ? 'Array' : typeof props.typeList.value); // 判断是否为数组
});

defineExpose({
  formRef,
  form,
  validateForm,
  resetForm
});
</script>

<style scoped>
.add-admin-form {
  padding: 20px;
}
</style>